app.controller('PerformanceCtrl', [
    '$scope', 'alertService', 'performanceService',
    function ($scope, alertService, performanceService) {
        $scope.page = {
            index: 1,
            size: 10,
            total: 0
        };
        $scope.searchForm = {
            start: 0,
            end: new Date()
        };
        $scope.searchForm.start = new Date($scope.searchForm.end.getFullYear(), $scope.searchForm.end.getMonth(), 1);

        function loadPerformances(index) {
            if ($scope.searchForm.start > $scope.searchForm.end) {
                alertService.add('开始日期不能大于结束日期');
                return;
            }
            performanceService.listAsync($scope.searchForm.title, $scope.searchForm.start,
                $scope.searchForm.end, index || $scope.page.index, $scope.page.size)
                .then(function (result) {
                    $scope.performanceList = result.data;
                    $scope.page.total = result.total;
                    if (result.total == 0 && index == 1) {
                        alertService.add("没有查询到数据");
                    }
                }, alertService.error);
        }

        $scope.$watch('page.index', function (newVal, oldVal) {
            loadPerformances();
        });

        $scope.$watch('page.size', function (newVal, oldVal) {
            if (!newVal || newVal === oldVal) return;
            loadPerformances();
        });

        $scope.search = function () {
            loadPerformances(1);
        };

        $scope.$watch('selectedIndex', function (newVal, oldVal) {
            if (!newVal || newVal === oldVal) return;
        });

        $scope.openCalendar = function ($event, target) {
            $event.preventDefault();
            $event.stopPropagation();
            if (target === 'start') {
                $scope.isStartOpen = true;
            }
            else if (target === 'end') {
                $scope.isEndOpen = true;
            }
        };
        
        $scope.enable=function(performance){
            performanceService.enableAsync(performance.Id,performance.Enabled)
                .then(function(result){
                   if(result) performance.Enabled=!performance.Enabled;
                },alertService.error);
        };
    }
]);

app.controller('PerformanceEditCtrl', [
    '$scope', 'alertService', 'performanceService', '$stateParams','fileService','$q',
    function ($scope, alertService, performanceService, $stateParams, fileService,$q) {
        $scope.performance = { Title: '数据加载中。。。', Id: $stateParams.id };

        $scope.editotrConfig = {
            //这里可以选择自己需要的工具按钮名称,此处仅选择如下五个
            toolbars: [['FullScreen', 'Source', 'Undo', 'Redo', 'Bold', 'test']],
            //focus时自动清空初始化时的内容
            autoClearinitialContent: true,
            //关闭字数统计
            wordCount: false,
            //关闭elementPath
            elementPathEnabled: false
        }

        if ($scope.performance.Id > 0) {
            performanceService.getAsync($scope.performance.Id)
                .then(function (result) {
                    $scope.performance = result;
                }, function(x){
                    alertService.error(x+' 稍后将返回上一页');
                    setTimeout(function(){
                        history.go(-1);
                    },5e3);                    
                });
        }else{
             $scope.performance.Title='新增文艺演出';
        }

        $scope.back = function() {
            window.history.back(-1);
        };

        $scope.submit = function () {
            $q.all([
               function () {
                   var defer1 = $q.defer();
                   fileService.upload($scope.ThumbImage.file)
                       .then(function (url) {
                           if (url) $scope.performance.Thumb = url;
                           defer1.resolve();
                       }, function (x) {
                           defer1.reject(x);
                       });
                   return defer1.promise;
               }(),
               function () {
                   var defer2 = $q.defer();
                   fileService.upload($scope.CoverImage.file)
                       .then(function (url) {
                           if (url) $scope.performance.ImageUrl = url;
                           defer2.resolve();
                       }, function (x) {
                           defer2.reject(x);
                       });
                   return defer2.promise;
               }()]
           ).then(function () {
               performanceService.createOrUpdateAsync($scope.performance)
                .then(function (result) {
                       if ($scope.performance.Id == 0) $scope.performance.Id = result;
                    alertService.success('提交成功');
                }, alertService.error);
           },
               alertService.error
           );
        };
    }
]);


app.factory('performanceService', [
    '$http', '$q',
    function ($http, $q) {
        var self = {};

        self.listAsync = function (title, start, end, pageIndex, pageSize) {
            var defer = $q.defer();
            $http({
                url: '/api/Performance/Search',
                params: { title: title || '', start: moment(start).format('YYYY-MM-DD'), end: moment(end).format('YYYY-MM-DD'), pageIndex: pageIndex, pageSize: pageSize }
            }).success(function (result) {
                if (result.Code >= 0) {
                    defer.resolve({ total: result.Code, data: result.Data });
                } else {
                    defer.reject(result.Message);
                }
            }).error(function (x) {
                defer.reject('查询演出列表失败');
            });

            return defer.promise;
        };

        self.getAsync = function (id) {
            var defer = $q.defer();
            $http({
                url: '/api/Performance',
                params: { id: id }
            }).success(function (result) {
                if (result.Code >= 0) {
                    defer.resolve(result.Data);
                } else {
                    defer.reject(result.Message);
                }
            }).error(function (x) {
                defer.reject('查询演出失败');
            });

            return defer.promise;
        };

        self.createOrUpdateAsync = function (model) {
            if (angular.isDate(model.ShowTime)) {
                model.ShowTime = moment(model.ShowTime).format('YYYY-MM-DD HH:mm');
            }
            var submitUrl = '/api/Performance/' + (model.Id > 0 ? 'update' : 'create');
            var defer = $q.defer();
            $http({
                url: submitUrl,
                method: 'Post',
                data: model
            }).success(function (result) {
                if (result.Code >= 0) {
                    defer.resolve(result.Code);
                } else {
                    defer.reject(result.Message);
                }
            }).error(function (x) {
                defer.reject('提交失败，请稍后再试');
            });
            return defer.promise;
        };

        function upload(file) {
            if (!angular.isDefined(file)) return '';
            var defer = $q.defer();
            var fileHttpConfig = {
                method: 'POST',
                url: '/api/File'
            };

            fileHttpConfig.data = file.data;
            $http(fileHttpConfig)
                .success(function (result) {
                    if (result.Code >= 0) {
                        defer.resolve(result.Message);
                    } else {
                        defer.reject(result.Message);
                    }
                })
                .error(function (x) {
                    defer.reject('上传文件失败');
                });
            return defer.promise;
        }
        
        self.enableAsync=function(performanceId,enabled){            
            var config={
                method:'POST',
                url:'/api/performance/'+(enabled?'delete':'resume'),
                params:{id:performanceId}
            }
            var defer=$q.defer();
            $http(config)
                .success(function(result){
                    if(result.Code>=0) defer.resolve(result.Data);
                    else defer.reject(result.Message);
                })
                .error(function(x){
                    defer.reject('操作失败，请稍后再试');
                    console.error(x)
                });
            return defer.promise;
        };

        return self;
    }
]);